#!/bin/bash 
set -e

TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage3}
SRC=${SRC:-/sources}

name=bzip2
version=1.0.8

rm -rf $TMP
mkdir -p $TMP $LOG

tar xf $SRC/$name-$version.tar.gz -C $TMP

{ time \
   {

    cd $TMP/$name-$version
    
    patch -Np1 -i $SRC/$name-$version-install_docs-1.patch

    sed -i 's@\(ln -s -f \)$(PREFIX)/bin/@\1@' Makefile
    
    sed -i "s@(PREFIX)/man@(PREFIX)/share/man@g" Makefile
    
    make -f Makefile-libbz2_so
    make clean
    
    make

    make PREFIX=/usr install
    
    cp -v bzip2-shared /bin/bzip2
    cp -av libbz2.so* /lib
    ln -sv ../../lib/libbz2.so.1.0 /usr/lib/libbz2.so
    rm -v /usr/bin/{bunzip2,bzcat,bzip2}
    ln -sv bzip2 /bin/bunzip2
    ln -sv bzip2 /bin/bzcat

    rm -fv /usr/lib/libbz2.a

    }
} 2>&1 | tee $name.log
    
[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
